<template>
  <div>
      <Upload
        ref="upload"
        :before-upload="handleUpload"
        :default-file-list="defaultList"
        :on-remove="remove"
        :on-preview="detail"
        :class="isUpload?'':'hides'"
        v-if="!isEdit"
        action="/study/index/merge">
        <Button icon="ios-cloud-upload-outline">选择视频上传</Button>
      </Upload>
    <div v-if="isEdit">
      <template v-if="defaultList.length >0">
        <div v-for="(item,index) in defaultList" :key="index">
          <div style="cursor: pointer;color: #1e88e5" @click="go(item.url)">{{item.name}}</div>
        </div>
      </template>
      <template v-else>
        <div>暂无数据</div>
      </template>
    </div>
    <Modal title="视频预览" v-model="isShow" class="modal-img-view">
        <video-player v-if="isShow" class="video-player vjs-custom-skin"
                       ref="videoPlayer"
                       :playsinline="true"
                       :options="playerOptions"
        ></video-player>
        <div slot="footer"></div>
      </Modal>
  </div>
</template>
<script>
  import { doPost,merge } from '@/api/video'
  export default {
  props: ["value","isEdit"],
  data() {
    return {
      file:null,
      adress:[],
      defaultList:[],
      isShow:false,
      isUpload:true,
      playerOptions : {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type:"video/mp4",
          src:''//地址（必填）,
        }],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  //全屏按钮
        }
      },
    };
  },
  watch: {
    value: function(newVal, oldVal) {
      let self = this;
      if (newVal && newVal !== oldVal) {
        let arr = newVal.indexOf(",") !== -1 ? newVal.split(',') : [newVal];
        let result = [];
        arr.forEach((x,index) => {
          let item = x.split('/')[4];
          result.push({
            url:x,
            name:item
          })
        });
        self.defaultList = result;
      }else {
        self.defaultList = [];
      }
      self.isShowIcon();
    },
    defaultList(val,old) {
      if(val) {
        this.isShowIcon();
      }
    }
  },
  methods: {
  isShowIcon() {
    if (this.defaultList.length === 0) {
      this.isUpload = true;
    } else {
      this.isUpload = false;
    }
  },
  handleUpload (file) {
    this.getTimes(file);
    if(file.type === 'video/mp4') {
      this.file = file;
      this.PostFile(file,0);
      return false;
    }else {
      this.$Message.error('只支持MP4格式上传');
    }
  },
    getTimes(file) {
      var content = file;
      //获取录音时长
      var url = URL.createObjectURL(content);
      //经测试，发现audio也可获取视频的时长
      var audioElement = new Audio(url);
      audioElement.addEventListener("loadedmetadata", (_event) => {
        let length = parseInt(audioElement.duration);
        this.$emit('videoLength',length)
      });
    },
  //执行分片上传
  PostFile(file,i, uuid){
    let that = this;
    let name = file.name,                           //文件名
      size = file.size,                           //总大小shardSize = 2 * 1024 * 1024,
      shardSize = 10 * 1024 * 1024,                //以2MB为一个分片,每个分片的大小
      shardCount = Math.ceil(size / shardSize);   //总片数
    if(i >= shardCount){
      return;
    }
    //判断uuid是否存在
    if (uuid == undefined || uuid == null) {
      uuid = this.guid();
    }
    //console.log(size,i+1,shardSize);  //文件总大小，第一次，分片大小//
    let start = i * shardSize;
    let end = start + shardSize;
    let packet = file.slice(start, end);  //将文件进行切片
    /*  构建form表单进行提交  */
    let form = new FormData();
    form.append("uuid", uuid);// 前端生成uuid作为标识符传个后台每个文件都是一个uuid防止文件串了
    form.append("data", packet); //slice方法用于切出文件的一部分
    form.append("name", name);
    form.append("totalSize", size);
    form.append("total", shardCount); //总片数
    form.append("index", i + 1); //当前是第几片
    doPost(form)
      .then(msg => {
        /*  表示上一块文件上传成功，继续下一次  */
        if (msg.code == 201) {
          form = '';
          i++;
          that.PostFile(file, i, uuid);
        } else if (msg.code == 502) {
          form = '';
          /*  失败后，每2秒继续传一次分片文件  */
          setInterval(function () { that.PostFile(file, i, uuid) }, 2000);
        } else if (msg.code == 200) {
          this.finished = true
          that.merge(uuid, name)
          console.log("上传成功");
        } else if (msg.code == 500) {
          console.log('第'+msg.i+'次，上传文件有误！');
        } else {
          console.log('未知错误');
        }
      });
},
  merge(uuid, fileName) {
    merge({uuid: uuid, newFileName: fileName})
      .then(msg => {
        this.adress = [];
        if(msg.code == 200) {
          this.adress.push({
            url:msg.filePath,
            name: this.file.name
          });
          this.defaultList = this.adress;
          this.$emit('video',this.adress);
        }
      });
  },
  detail(file) {
    this.playerOptions['sources'][0]['src'] = `${file.url.trim()}`;
    this.playerOptions['sources'][0]['type'] = ``;
    this.isShow = true
  },
  go(url){
    this.playerOptions['sources'][0]['src'] = `${url.trim()}`;
    this.playerOptions['sources'][0]['type'] = ``;
    this.isShow = true
  },
  remove( file, fileList) {
    this.adress.forEach((x,index) => {
      if(x.url === file.url) {
        this.adress.splice(index,1)
      }
    });
    this.defaultList.forEach((x,index) => {
      if(x.url === file.url) {
        this.defaultList.splice(index,1)
      }
    });
  },
  guid() {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = Math.random() * 16 | 0,
        v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  },
},
};
</script>
<style scoped>
  .hides >>> .ivu-upload-select {
    display: none;
  }
</style>
